// controllers/tableController.js
const { log } = require('console');
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');
const crypto = require('crypto');

// 获取所有桌台
const getAllTables = async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM tables');
    sendResponse(res, 200, '获取桌台成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取桌台失败', error.message);
  }
};

// 扫描桌台二维码
const scanTableQrCode = async (req, res) => {
  const { qrCode } = req.body;
  try {
    const [rows] = await pool.execute('SELECT * FROM tables WHERE qr_code = ?', [qrCode]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '桌台未找到');
    }
    sendResponse(res, 200, '扫描桌台二维码成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '扫描桌台二维码失败', error.message);
  }
};

// 获取单个桌台
const getTableById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute('SELECT * FROM tables WHERE id = ?', [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '桌台未找到');
    }
    sendResponse(res, 200, '获取桌台成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '获取桌台失败', error.message);
  }
};

// 创建桌台
const createTable = async (req, res) => {
  const { table_number, status } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查桌台编号是否已存在
    const [existing] = await connection.execute('SELECT * FROM tables WHERE table_number = ?', [table_number]);
    if (existing.length > 0) {
      await connection.rollback();
      return sendResponse(res, 409, '桌台编号已存在');
    }
    // 生成二维码 (这里简化处理，实际项目中可能需要调用二维码生成库)
    const qrCode = `https://example.com/table/${crypto.randomBytes(8).toString('hex')}`;
    const [result] = await connection.execute(
      'INSERT INTO tables (table_number, status, qr_code) VALUES (?, ?, ?)',
      [table_number, status || 0, qrCode]
    );
    await connection.commit();
    sendResponse(res, 201, '创建桌台成功', { id: result.insertId, qr_code: qrCode });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建桌台失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新桌台
const updateTable = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查桌台是否存在
    const [tables] = await connection.execute('SELECT * FROM tables WHERE id = ?', [id]);
    if (tables.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '桌台未找到');
    }

    const [result] = await connection.execute(
      'UPDATE tables SET  status = ? WHERE id = ?',
      [status, id]
    );
    await connection.commit();
    sendResponse(res, 200, '更新桌台成功');
  } catch (error) {
    console.log(error)

    await connection.rollback();
    sendResponse(res, 500, '更新桌台失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除桌台
const deleteTable = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查桌台是否存在
    const [tables] = await connection.execute('SELECT * FROM tables WHERE id = ?', [id]);
    if (tables.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '桌台未找到');
    }
    // 检查是否有未完成的订单
    const [orders] = await connection.execute('SELECT * FROM orders WHERE table_id = ? AND status NOT IN (3, 4)', [id]);
    if (orders.length > 0) {
      await connection.rollback();
      return sendResponse(res, 400, '该桌台有未完成的订单，无法删除');
    }
    const [result] = await connection.execute('DELETE FROM tables WHERE id = ?', [id]);
    await connection.commit();
    sendResponse(res, 200, '删除桌台成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除桌台失败', error.message);
  } finally {
    connection.release();
  }
};

// 生成新的桌台二维码
const generateTableQrCode = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查桌台是否存在
    const [tables] = await connection.execute('SELECT * FROM tables WHERE id = ?', [id]);
    if (tables.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '桌台未找到');
    }
    // 生成新的二维码
    const qrCode = `https://example.com/table/${crypto.randomBytes(8).toString('hex')}`;
    await connection.execute('UPDATE tables SET qr_code = ? WHERE id = ?', [qrCode, id]);
    await connection.commit();
    sendResponse(res, 200, '生成二维码成功', { qr_code: qrCode });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '生成二维码失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新桌台状态
const updateTableStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查桌台是否存在
    const [tables] = await connection.execute('SELECT * FROM tables WHERE id = ?', [id]);
    if (tables.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '桌台未找到');
    }
    await connection.execute('UPDATE tables SET status = ? WHERE id = ?', [status, id]);
    await connection.commit();
    sendResponse(res, 200, '更新桌台状态成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新桌台状态失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  getAllTables,
  getTableById,
  createTable,
  updateTable,
  deleteTable,
  generateTableQrCode,
  updateTableStatus,
  scanTableQrCode

};